package com.lt.lumentracks.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lt.lumentracks.entity.po.PostTag;
import com.lt.lumentracks.mapper.PostTagMapper;
import com.lt.lumentracks.service.IPostTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 帖子标签表（关联表） 服务实现类
 * </p>
 *
 * @author swl
 * @since 2025-07-28
 */
@Service
public class PostTagServiceImpl extends ServiceImpl<PostTagMapper, PostTag> implements IPostTagService {

    // 更新帖子标签
    @Transactional
    @Override
    public void updatePostTag(Integer postId, List<Integer> newTagIdList) {
        if (newTagIdList == null || newTagIdList.isEmpty()) {
            return;
        }

        // 1.查询数据库，获取该帖子的标签列表
        QueryWrapper<PostTag> qw_pt = new QueryWrapper<PostTag>().eq("post_id", postId);
        List<PostTag> PostTagList = this.list(qw_pt);
        List<Integer> oldTagIdList = PostTagList.stream().map(PostTag::getTagId).toList();


        // 2.对比新旧标签集合
        // 找出要删除的标签集合（旧集合有，新集合没有，那就是要删除的）
        List<Integer> delTagIdList = oldTagIdList.stream()
                .filter(tagId -> !newTagIdList.contains(tagId))
                .toList();

        // 找出要添加的标签集合（旧集合没有，新集合有，那就是要新增的）
        List<Integer> addTagIdList = newTagIdList.stream()
                .filter(tagId -> !oldTagIdList.contains(tagId))
                .toList();

        // 两个集合里都有的话就是不变的，不用管


        // 3.执行数据库操作
        // 执行删除操作（删除要传入的是PostTag的id列表，上面获取的是PostTag的tagId列表，还要再做一次转换）
        if(!delTagIdList.isEmpty()){
            List<Integer> delIdList = PostTagList.stream()
                    .filter(pt -> delTagIdList.contains(pt.getTagId()))
                    .map(PostTag::getId)
                    .toList();
            this.removeByIds(delIdList);
        }

        // 执行新增操作
        if(!addTagIdList.isEmpty()){
            List<PostTag> addPostTagList = new ArrayList<>();
            for (Integer tagId : addTagIdList) {
                PostTag pt = new PostTag();
                pt.setPostId(postId);
                pt.setTagId(tagId);
                addPostTagList.add(pt);
            }
            this.saveBatch(addPostTagList);
        }
    }
}
